package com.tianyadu.security.core.authentication.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @FileName: SmsCodeAuthenticationSecurityConfig
 * @Description: 短信验证码配置类
 * @author: xueyj
 * @create: 2018-12-13 18:45
 */
@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    /** 登陆成功 */
    @Autowired
    AuthenticationSuccessHandler authSuccessHandler;

    /** 登陆失败 */
    @Autowired
    AuthenticationFailureHandler authFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
      * @Description: 添加拦截及认证信息
      * @param:
      * @return:
      * @author:
      * @date:   2018/12/13 18:54
      */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //  初始化短信验证码拦截器
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        //  设置短信验证码拦截器authenticationManager
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //  设置认证成功处理器
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authSuccessHandler);
        //  设置认证失败处理器
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authFailureHandler);

        //
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        //  添加用户查询服务信息
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

        //  添加处理短信验证拦截器信息
        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}